package com.md.mainpage.ui;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.reflect.TypeToken;
import com.living.player.PlayUtils;
import com.md.album.db.SelfAlbumManager;
import com.md.basedpc.PHSizeUtils;
import com.md.basedpc.StringUtils;
import com.md.basedpc.base.BaseActivity;
import com.md.basedpc.json.JsonUtils;
import com.md.basedpc.persistence.PHSPUtil;
import com.md.livingwidget.emptyview.PHEmptyViewUI;
import com.md.livingwidget.flowlabel.PHFlowLabelLayout;
import com.md.mainpage.R;
import com.md.mainpage.adapter.SearchAdapter2;
import com.md.mainpage.interfaces.SearchContract;
import com.md.mainpage.presenter.SearchPresenter;
import com.md.network.api.Audio;
import com.md.network.api.SearchResult;
import com.md.network.api.SearchedAudio;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyue
 * crated 2021/5/30
 * desc 搜索页面
 * 搜索接口分页，每次获取20条记录
 * TODO 动画改为上下滑动进出
 */
@Route(path = "/main/search")
public class SearchActivity extends BaseActivity implements TextView.OnEditorActionListener, OnItemChildClickListener, TextWatcher, View.OnClickListener, SearchContract.View {
    private String TAG = "SearchActivity";
    private final String history_labels = "SearchActivity_labels";
    public static final String key_alblumId = "SearchActivity_key_alblumId";
    private static final int MAX_NUM_PAGE = 20; //每页最多展示的搜索记录

    private EditText searchEdit;
    private FrameLayout fltCancelContainer;
    private LinearLayout lltSearchTip;
    private ImageView ivLeftSearchIcon;
    private TextView tvCancel;
    private SmartRefreshLayout refreshLayout;

    private View layout_search_history;
    private PHFlowLabelLayout phFlowLabelLayout;
    private RecyclerView recResult;
    private SearchPresenter mPrestner;
    private SearchAdapter2 searchAdapter;
    private String keyWord;
    private PHEmptyViewUI phEmptyViewUI;
    private List<String> labelsHistory = new ArrayList<>();
    String ablumId = "";
    private int currentPage;
    private int maxPage; // 最大页数，从0开始
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ARouter.getInstance().inject(this);
        setStatusBarColor(false, getResources().getColor(com.md.livingwidget.R.color.white));
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        PHSPUtil.getInstance().putString(history_labels, JsonUtils.toJson(labelsHistory));
        super.onDestroy();
        mPrestner.detachView();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        showLeftSearchIcon(true);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        showLeftSearchIcon(true);
    }

    @Override
    public void afterTextChanged(Editable s) {
        keyWord = searchEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(keyWord)) {
            showCancelIcon(true);
        } else {
            showCancelIcon(false);
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
            String searchWord = searchEdit.getText().toString().trim();
            if (TextUtils.isEmpty(searchWord)) {
                Toast.makeText(this, getString(R.string.main_input_valid_world), Toast.LENGTH_SHORT).show();
                return false;
            }
            //每次点击「搜索」按钮都是从1页开始搜索，且重置keyworld
            keyWord = searchWord;
            currentPage = 0;
            maxPage = 0;
            search(++currentPage,searchWord);
            return true;
        }
        return false;
    }

    private void search(int targetPage,String keyWord) {
        Log.e(TAG,"MAXPAGE = "+maxPage+" targetPage = "+targetPage);
        mPrestner.search(targetPage, MAX_NUM_PAGE, keyWord);
    }

    private void initView() {
        searchEdit = findViewById(R.id.searchEdit);
        fltCancelContainer = findViewById(R.id.fltCancelContainer);
        fltCancelContainer.setOnClickListener(this);
        lltSearchTip = findViewById(R.id.lltSearchTip);
        ivLeftSearchIcon = findViewById(R.id.ivLeftSearchIcon);
        layout_search_history = findViewById(R.id.layout_search_history);
        phFlowLabelLayout = findViewById(R.id.flowLayout);
        findViewById(R.id.iv_search_history_delete).setOnClickListener(this);

        searchEdit.setOnEditorActionListener(this);
        searchEdit.addTextChangedListener(this);
        searchEdit.setSelection(searchEdit.getText().length());
        tvCancel = findViewById(R.id.tvCancel);
        tvCancel.setOnClickListener(this::onClick);
        recResult = findViewById(R.id.recResult);
        recResult.setLayoutManager(new LinearLayoutManager(this));
        phEmptyViewUI = new PHEmptyViewUI(this);
        searchAdapter = new SearchAdapter2();
        recResult.setAdapter(searchAdapter);
        searchAdapter.setEmptyView(phEmptyViewUI);
        searchAdapter.setOnItemChildClickListener(this);

        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (!TextUtils.isEmpty(keyWord) && currentPage < maxPage){
                    search(++currentPage,keyWord);
                }else {
                    refreshLayout.finishLoadMore();
                }
            }
        });
    }

    private void initData() {
        if (getIntent().hasExtra(key_alblumId)) {
            ablumId = getIntent().getStringExtra(key_alblumId);
        }
        searchAdapter.setShowAdd(!TextUtils.isEmpty(ablumId));
        mPrestner = new SearchPresenter();
        mPrestner.attachView(this);
        searchEdit.requestFocus();
        showLeftSearchIcon(true);
        int paddingV = PHSizeUtils.dp2px(this, 4);
        int paddingH = PHSizeUtils.dp2px(this, 8);
        phFlowLabelLayout.setLabelTextPadding(paddingH, paddingV, paddingH, paddingV);

        ArrayList<String> list = JsonUtils.fromJson(PHSPUtil.getInstance().getString(history_labels), new TypeToken<List<String>>() {
        }.getType());
        if (list != null) {
            labelsHistory.addAll(list);
        }
        phFlowLabelLayout.showTag(labelsHistory, new PHFlowLabelLayout.ItemClickListener() {
            @Override
            public void onClick(CharSequence currentSelectedkeywords, List<CharSequence> allSelectedKeywords, int postion) {
                //搜索历史消息
                currentPage = 0;
                keyWord = currentSelectedkeywords.toString();
                search(++currentPage,keyWord);
            }
        });
        layout_search_history.setVisibility(labelsHistory.size() > 0 ? View.VISIBLE : View.GONE);
    }

    private void showCancelIcon(boolean isShow) {
        if (isShow) fltCancelContainer.setVisibility(View.VISIBLE);
        else fltCancelContainer.setVisibility(View.GONE);
    }

    private void showLeftSearchIcon(boolean isShow) {
        if (isShow) {
            ivLeftSearchIcon.setVisibility(View.VISIBLE);
            lltSearchTip.setVisibility(View.GONE);
        } else {
            ivLeftSearchIcon.setVisibility(View.GONE);
            lltSearchTip.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.fltCancelContainer) {
            searchEdit.setText("");
        } else if (id == R.id.tvCancel) {
            finish();
        } else if (id == R.id.iv_search_history_delete) {
            labelsHistory.clear();
            phFlowLabelLayout.showTag(labelsHistory, null);
            layout_search_history.setVisibility(labelsHistory.size() > 0 ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void showResult(String keyWord, @org.jetbrains.annotations.Nullable SearchResult result) {
        refreshLayout.finishLoadMore();
        if (result != null) {
            countMaxPage(result.getTotal());
            List<SearchedAudio> audios = result.getList();
            boolean isResNotBlank = audios != null && audios.size() > 0;
            layout_search_history.setVisibility(View.GONE);
            recResult.setVisibility(View.VISIBLE);
            if (isResNotBlank) {
                if (!TextUtils.isEmpty(ablumId)) {
                    for (SearchedAudio searchedAudio : audios) {
                        searchedAudio.setAddAlbum(SelfAlbumManager.getIns().isAudioExist(searchedAudio.getId()));
                    }
                }
                searchAdapter.setKeywords(keyWord);
                List<SearchedAudio> presentData = new ArrayList<>();
                //先获取已经展示的数据，再添加新搜索到数据
                //使用全局变量维护起来很麻烦，所以使用局部变量
                if (searchAdapter.getData() !=null && searchAdapter.getData().size() > 0){
                    presentData.addAll(searchAdapter.getData());
                }
                presentData.addAll(audios);
                searchAdapter.setNewInstance(presentData);
            } else {
                String tip = String.format(getResources().getString(R.string.main_no_search_data), StringUtils.append("\"", keyWord, "\""));
                phEmptyViewUI.setEmptyText(tip);
            }
            if (!labelsHistory.contains(keyWord)) {
                labelsHistory.add(keyWord);
                if (labelsHistory.size() > 30) {
                    labelsHistory = labelsHistory.subList(0, 29);
                }
            }
        }
    }
    //点击"搜索"就视为更改了搜索关键字，重新计算最大页数
    //计算最大页数。当前设定每页展示MAX_NUM_PAGE = 20条记录，如果搜索结果共19条，那么最大页数=1；如果共20条，最大页数=1；如果21条，最大页数=2；
    //以上三种情况中，当搜索结果是是MAX_NUM_PAGE = 20条整数倍时可以直接计算出结果，其他情况需要判断
    private void countMaxPage(int totalCount) {
        if (maxPage==0 && totalCount>0){
            maxPage = totalCount/MAX_NUM_PAGE;
            if (maxPage == 0 || maxPage * MAX_NUM_PAGE < totalCount){
                maxPage++;
            }
        }
    }

    @Override
    public void showError(@NotNull String errorMsg) {
        if (refreshLayout.isLoading()){
            refreshLayout.finishLoadMore();
        }
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
    }

//    private List<Audio> convertToAudioList(List<SearchedAudio> list) {
//        List<Audio> result = new ArrayList<>();
//        if (list != null && list.size() > 0) {
//            for (SearchedAudio audio : list) {
//                result.add(convertToAudio(audio));
//            }
//        }
//        return result;
//    }

    private Audio convertToAudio(SearchedAudio searchedAudio) {
        if (searchedAudio != null) {
            Audio audio = new Audio(searchedAudio.getId(),
                    searchedAudio.getAuthor(),
                    "",
                    searchedAudio.getDesc(),
                    searchedAudio.getEncrypt(),
                    searchedAudio.getName(),
                    searchedAudio.getAudioUrl());
            return audio;
        }
        return null;
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        SearchedAudio searchedAudio = searchAdapter.getItem(position);
        Audio audio = convertToAudio(searchedAudio);
        if (view.getId() == R.id.cltSearchResult) {
            PlayUtils.intentTo(getmContext(), null, audio);
        } else if (view.getId() == R.id.iv_search_addabulm) {
            if (!TextUtils.isEmpty(ablumId)) {
                SelfAlbumManager.getIns().saveAudioToAlbum(ablumId, audio);
                searchedAudio.setAddAlbum(true);
                searchAdapter.notifyItemChanged(position);
//            PHToast.shotBigToast(getmActivity(), "歌曲已添加过");
            }
        }
    }


}
